#!/bin/bash

# 使用代理启动 Claude Code UI 容器
# 该脚本强制所有请求通过指定的代理 API

set -e

# 颜色输出
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'

# 配置
ANTHROPIC_API_KEY="${1:-sk-ant-api03-l4F2v8h2gCMPsVI9YfXx0cbnio_BoQM_CfgDyju3so33my6jf84xLZVGkgjgTARaajLt8DC5fzXpRoaEGFxodQ}"
ANTHROPIC_BASE_URL="${2:-https://api.aicodemirror.com/api/claudecode}"
PROJECT_PATH="${3:-/Users/c/projects/test-project}"
PROJECT_NAME="${4:-test-project}"
CONTAINER_NAME="claude-test"
PORT="3001"
# Claude 配置独立存储目录(不在项目下,避免被挂载两次)
CLAUDE_DATA_DIR="$HOME/.claude-container-data/$CONTAINER_NAME"

echo -e "${GREEN}========================================${NC}"
echo -e "${GREEN}Claude Code UI 代理模式启动${NC}"
echo -e "${GREEN}========================================${NC}"
echo ""
echo "配置信息："
echo "  API Key: ****${ANTHROPIC_API_KEY: -4}"
echo "  代理 API: $ANTHROPIC_BASE_URL"
echo "  项目路径: $PROJECT_PATH"
echo "  项目名称: $PROJECT_NAME"
echo "  Claude 数据: $CLAUDE_DATA_DIR"
echo ""

# 确保项目目录存在
if [ ! -d "$PROJECT_PATH" ]; then
    echo -e "${YELLOW}创建项目目录...${NC}"
    mkdir -p "$PROJECT_PATH"
    echo "# Test Project" > "$PROJECT_PATH/README.md"
fi

# 创建 Claude 独立数据目录结构
mkdir -p "$CLAUDE_DATA_DIR/.claude"
echo -e "${GREEN}✓ Claude 数据目录已创建${NC}"

# 创建 API Key 授权文件 (放在根目录下,与 .claude 目录平级)
API_KEY_SUFFIX="${ANTHROPIC_API_KEY: -20}"
cat > "$CLAUDE_DATA_DIR/.claude.json" << EOF
{
  "customApiKeyResponses": {
    "approved": [
      "$API_KEY_SUFFIX"
    ]
  }
}
EOF
echo -e "${GREEN}✓ API Key 配置已创建 (.claude.json)${NC}"

# 停止旧容器
if docker ps -a | grep -q $CONTAINER_NAME; then
    echo -e "${YELLOW}停止旧容器...${NC}"
    docker stop $CONTAINER_NAME 2>/dev/null || true
    docker rm $CONTAINER_NAME 2>/dev/null || true
fi

echo -e "${YELLOW}启动新容器...${NC}"

# 启动容器，设置 ANTHROPIC_BASE_URL 强制使用代理
docker run -d \
  --name $CONTAINER_NAME \
  -p $PORT:3001 \
  -e SINGLE_PROJECT_MODE=true \
  -e PROJECT_NAME="$PROJECT_NAME" \
  -e PROJECT_PATH=/project \
  -e ANTHROPIC_API_KEY="$ANTHROPIC_API_KEY" \
  -e ANTHROPIC_BASE_URL="$ANTHROPIC_BASE_URL" \
  -e ANTHROPIC_AUTH_TOKEN="" \
  -v "$PROJECT_PATH:/project" \
  -v "$CLAUDE_DATA_DIR/.claude:/root/.claude" \
  -v "$CLAUDE_DATA_DIR/.claude.json:/root/.claude.json" \
  claude-code-ui:single-project

sleep 5

# 检查容器状态
if docker ps | grep -q $CONTAINER_NAME; then
    echo -e "${GREEN}✓ 容器启动成功！${NC}"
    echo ""
    echo -e "访问地址: ${YELLOW}http://localhost:$PORT${NC}"
    echo ""
    echo "容器日志："
    echo -e "${GREEN}----------------------------------------${NC}"
    docker logs --tail 20 $CONTAINER_NAME
    echo -e "${GREEN}----------------------------------------${NC}"
else
    echo -e "${RED}✗ 容器启动失败${NC}"
    docker logs $CONTAINER_NAME
    exit 1
fi
